package com.pxmeta.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.app.entity.AppVersion;
import com.pxmeta.app.mapper.AppVersionMapper;
import com.pxmeta.app.service.IAppVersionService;
import com.pxmeta.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements IAppVersionService {


    @Override
    public List<AppVersion> getListByPlatform(String platform) {
        LambdaQueryWrapper<AppVersion> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AppVersion::getPlatform, platform)
                .orderByDesc(AppVersion::getCreateTime);
        return this.list(wrapper);
    }

    /**
     * 获取最新版本
     * @param platform
     * @return
     */
    @Override
    public AppVersion getNewestVersion(String platform) {
        LambdaQueryWrapper<AppVersion> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AppVersion::getPlatform, platform)
                .eq(AppVersion::getIsNewest, 1);
        return this.getOne(wrapper,false);
    }

    @Override
    @Transactional
    public void updateVersion(Integer id, String explain, Integer isNewest) {
        AppVersion appVersion = this.getById(id);

        if (StringUtils.isNotBlank(explain)){
            appVersion.setVersionExplain(explain);
        }
        if (isNewest != null){
            appVersion.setIsNewest(isNewest);
            if (isNewest == 1){
                //设为最新，将其他版本去除最新。
                LambdaQueryWrapper<AppVersion> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(AppVersion::getPlatform, appVersion.getPlatform())
                        .eq(AppVersion::getIsNewest, 1);
                List<AppVersion> list = this.list(wrapper);
                list.forEach(l->l.setIsNewest(0));
                this.updateBatchById(list);
            }
        }
        this.updateById(appVersion);
    }
}
